package com.xxrl.hmwork.controller;

import com.xxrl.hmwork.commons.Jackson;
import com.xxrl.hmwork.domain.Homework;
import com.xxrl.hmwork.service.HomeworkService;
import com.xxrl.hmwork.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;


/**
 * 作业的crd
 * @author mis
 */
@RestController
@RequestMapping("/homework")
public class HomeworkController {

    private final StatisticsService statisticsService;

    private final HomeworkService homeworkService;

    @Autowired
    public HomeworkController(StatisticsService statisticsService, HomeworkService homeworkService) {
        this.statisticsService = statisticsService;
        this.homeworkService = homeworkService;
    }

    @GetMapping("list")
    public String list(
            @RequestParam(name = "page", defaultValue = "1") Integer page,
            @RequestParam(name = "limit", defaultValue = "20") Integer limit) {
        Page<Homework> list = homeworkService.list(PageRequest.of(page-1,limit));
        String json = Jackson.me().toJson(list.toList());
        statisticsService.totalHomework = list.getTotalElements();
        json = "{ \"items\":" +json + ", \"total\":" + list.getTotalElements()+"}";
        return json;
    }

    @PostMapping("save")
    public void save(Homework homework) {
        homeworkService.save(homework);
    }

    @PostMapping("delete")
    public void delete(@RequestParam(name = "oid") Long id) {
        homeworkService.delete(id);
    }
}
